//
//  SAFNetworking.m
//  TSBanPai
//
//  Created by wandong on 2017/10/16.
//  Copyright © 2017年 tingshan. All rights reserved.
//

#import "SAFNetworking.h"
#import "KF5SDK.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MBProgressHUD.h"
#import <Foundation/Foundation.h>

#import "LoginViewController.h"

@implementation SAFNetworking
//单例
+ (instancetype)shareInstance{
    static SAFNetworking *share;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        share = [SAFNetworking manager];
        share.requestSerializer=[AFHTTPRequestSerializer serializer];
        share.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
        share.responseSerializer.acceptableContentTypes = nil;
        //AFNetworking下 http 改 https后遇到出现Error Domain=NSURLErrorDomain Code=-999 "已取消" 错误
        //错误的原因 由于是证书没有 所以默认的afn安全策略是 不请求的
        AFSecurityPolicy *s = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        [s setValidatesDomainName:NO];
        share.securityPolicy = s;
        share.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        share.requestSerializer = [AFJSONRequestSerializer serializer];
        share.responseSerializer = [AFJSONResponseSerializer serializer];
        [share.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [share.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [share.requestSerializer setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] forHTTPHeaderField:@"Authorization"];
        [share.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        share.requestSerializer.timeoutInterval = 120.f;
        [share.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    });
    return share;
}

//post 请求
+ (void)POSTJSON:(NSString *)urlStr Paramter:(NSDictionary *)param  success:(successBlock)success failure: (failureBlock)failure{
    
    [SAFNetworking POSTJSON:urlStr Paramter:param success:success failure:failure progress:nil];
}

//post 请求带进度
+ (void)POSTJSON:(NSString *)urlStr Paramter:(NSDictionary *)param  success:(successBlock)success failure: (failureBlock)failure progress: (SActionBlock1)progress{
    
//    DLog(@"请求头部:%@\n请求地址:%@\n,请求参数:%@\n",[SAFNetworking shareInstance].requestSerializer.HTTPRequestHeaders,urlStr,[param description]);
    if (progress) {
        [[SAFNetworking shareInstance]POST:urlStr parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            progress(downloadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            DLog(@"成功返回:%@\n",[responseObject description]);
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"失败返回:%@\n",[error description]);
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSInteger statusCode = response.statusCode;
            if (statusCode == 401) {
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
                [KFUserManager deleteUser];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                    LoginViewController *LoVC = [[LoginViewController alloc]init];
                    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                    window.rootViewController= nav;
                });
                return;
            }
            if (failure) {
                failure(task.response,error);
            }
        }];
    }else{
        [[SAFNetworking shareInstance]POST:urlStr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            DLog(@"成功返回:%@\n",[responseObject description]);
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"失败返回:%@\n",[error description]);
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSInteger statusCode = response.statusCode;
            if (statusCode == 401) {
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
                [KFUserManager deleteUser];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                    LoginViewController *LoVC = [[LoginViewController alloc]init];
                    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                    window.rootViewController= nav;
                });
                return;
            }
            if (failure) {
                failure(task.response,error);
            }
        }];
    }
}

//PUT 请求
+ (void)PUTJSON:(NSString *)urlStr Paramter:(NSDictionary *)param  success:(successBlock)success failure: (failureBlock)failure{
    //    DLog(@"请求头部:%@\n请求地址:%@\n,请求参数:%@\n",[SAFNetworking shareInstance].requestSerializer.HTTPRequestHeaders,urlStr,[param description]);
    [[SAFNetworking shareInstance] PUT:urlStr parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"失败返回:%@\n",[error description]);
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
            [KFUserManager deleteUser];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                LoginViewController *LoVC = [[LoginViewController alloc]init];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                window.rootViewController= nav;
            });
            return;
        }
        if (failure) {
            failure(task.response,error);
        }
    }];
}

//get 请求
+ (void)GETJSON:(NSString *)urlStr Paramter:(NSDictionary *)param  success:(successBlock)success failure: (failureBlock)failure{
    [SAFNetworking GETJSON:urlStr Paramter:param success:success failure:failure progress:nil];
}

//get 请求带进度
+ (void)GETJSON:(NSString *)urlStr Paramter:(NSDictionary *)param  success:(successBlock)success failure: (failureBlock)failure  progress: (SActionBlock1)progress{
//    DLog(@"请求头部:%@\n请求地址:%@\n,请求参数:%@\n",[SAFNetworking shareInstance].requestSerializer.HTTPRequestHeaders,urlStr,[param description]);
    if (progress) {
        [[SAFNetworking shareInstance]GET:urlStr parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            progress(downloadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            DLog(@"成功返回:%@\n",[responseObject description]);
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"失败返回:%@\n",[error description]);
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSInteger statusCode = response.statusCode;
            if (statusCode == 401) {
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
                [KFUserManager deleteUser];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                    LoginViewController *LoVC = [[LoginViewController alloc]init];
                    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                    window.rootViewController= nav;
                });
                return;
            }
            if (failure) {
                failure(task.response,error);
            }
        }];
    }else{
        [[SAFNetworking shareInstance]GET:urlStr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            DLog(@"成功返回:%@\n",[responseObject description]);
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"失败返回:%@\n",[error description]);
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSInteger statusCode = response.statusCode;
            if (statusCode == 401) {
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"id"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"pwd"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"username"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"realname"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"headImage"];
                [KFUserManager deleteUser];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIWindow * window = [[[UIApplication  sharedApplication]delegate]window];// 获得根窗口
                    LoginViewController *LoVC = [[LoginViewController alloc]init];
                    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:LoVC];
                    window.rootViewController= nav;
                });
                return;
            }
            if (failure) {
                failure(task.response,error);
            }
        }];
    }
}

+ (NSString*)getJpgName:(int)num{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat =@"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@_%d.jpg", str,num];
    return fileName;
}

+ (NSString*)getFileName:(NSString*)filename num:(int)num{
    return num==0?filename:[NSString stringWithFormat:@"%@%d",filename,num+1];
}

+ (void)UPLOADDATA:(NSString *)urlStr Paramter:(NSDictionary *)param filename:(NSString*)filename file:(id)data success:(successBlock)success failure: (failureBlock)failure progress: (SActionBlock1)progress{
    
    if (!filename) {
        
        filename = @"uploadify";
    }
    
    [[SAFNetworking shareInstance]POST:urlStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([data isKindOfClass:[NSArray class]] && ((NSArray*)data).count > 0) {
            NSArray *mediaDatas = (NSArray*)data;
            NSObject *firstObj = [mediaDatas objectAtIndex:0];
            if ([firstObj isKindOfClass:[UIImage class]]) {    // 图片
                for(int i=0; i<mediaDatas.count; i++) {
                    UIImage *eachImg = [mediaDatas objectAtIndex:i];
                    //NSData *eachImgData = UIImagePNGRepresentation(eachImg);
                    NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 1);
//                    [formData appendPartWithFileData:eachImgData name:[SAFNetworking getFileName:filename num:i] fileName:[SAFNetworking getJpgName:(i+1)] mimeType:@"image/jpeg"];
                    [formData appendPartWithFileData:eachImgData name:filename fileName:[SAFNetworking getJpgName:(i+1)] mimeType:@"image/jpeg"];

                }
            }else if ([firstObj isKindOfClass:[NSData class]]){
                //图片data
                for(int i=0; i<mediaDatas.count; i++) {
                    [formData appendPartWithFileData:[mediaDatas objectAtIndex:i] name:[SAFNetworking getFileName:filename num:i] fileName:[SAFNetworking getJpgName:(i+1)] mimeType:@"image/jpeg"];
                }
            }else if ([firstObj isKindOfClass:[ALAsset class]]){
                // 视频
                ALAsset *asset = [mediaDatas objectAtIndex:0];
                if (asset !=nil) {
                    DLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url);
                    NSURL *url = [asset defaultRepresentation].url;
                    //                    NSError *theErro =nil;
                    //                    BOOL exportResult = [asset exportDataToURL:url error:&theErro];
                    //                    DLog(@"exportResult=%@", exportResult?@"YES":@"NO");
                    NSData *videoData = [NSData dataWithContentsOfURL:url];
                    [formData appendPartWithFileData:videoData name:@"video1" fileName:@"video1.mov" mimeType:@"video/quicktime"];
                }
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task.response,error);
        }
    }];
}
+ (void)UPLOADDATA:(NSString *)urlStr Paramter:(NSDictionary *)param file:(id)data success:(successBlock)success failure: (failureBlock)failure progress: (SActionBlock1)progress{
    [SAFNetworking UPLOADDATA:urlStr Paramter:param filename:nil file:data success:success failure:failure progress:progress];
}

+ (NSString *)getCurrentMonth{
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    
    NSArray *arr = [dateStr componentsSeparatedByString:@"-"];
    
    NSString *month = [NSString stringWithFormat:@"%@月",arr.lastObject];
    
    return month;
}

+ (AFURLSessionManager*)shareManager{
    static AFURLSessionManager *shareManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        shareManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    });
    return shareManager;
}

////下载文件+缓存 异步
//+ (NSURLSessionDownloadTask * )DOWNLOAD:(NSString*)urlStr Parameter:(NSDictionary *)param addition:(NSString*)addition filetype:(NSString*)filetype success:(SActionBlock1)success failure: (failureBlock)failure progress: (SActionBlock1)progress{
//    //查找本地有没有
//    id path = [SCache getFilePath:urlStr addition:nil];
//    NSURL *pathURL = [NSURL fileURLWithPath:path?:@""];
//    if (path && pathURL) {
//        success(pathURL);
//        DLog(@"本地路径：%@，绝对路径：%@",path,[pathURL absoluteString]);
//        return nil;
//    }
//    DLog(@"开始下载url：%@",urlStr);
//    // 1、 设置请求
//    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//    // 2、初始化
////    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
////    AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//
//    // 3、开始下载
//    NSURLSessionDownloadTask * task = [[SAFNetworking shareManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        if (progress) {
//            progress(downloadProgress);
//        }
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        //使用建议的路径
//        NSString * path = [SCache filePath:response.suggestedFilename];
//        NSLog(@"%@",path);
//        return [NSURL fileURLWithPath:path];//转化为文件路径
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        //如果下载的是压缩包的话，可以在这里进行解压
//        DLog(@"----%@---%d---%@",error.domain,error.code,error);
//        //下载成功
//        if (error == nil) {
//            if (success) {
//                //存储到本地 实际上存储的是文件名
//                [SCache saveFilePath:urlStr addition:nil filePath:response.suggestedFilename];
//                DLog(@"下载成功并保存在本地url：%@,文件名:%@",urlStr,response.suggestedFilename);
//                success(filePath);
//            }
//        }else{//下载失败的时候，只列举判断了两种错误状态码
//            NSString * message = nil;
//            if (error.code == - 1005) {
//                message = @"网络异常";
//            }else if (error.code == -1001){
//                message = @"请求超时";
//            }else{
//                message = @"未知错误";
//            }
//            if(failure){
//                failure(response,error);
//            }
//        }
//    }];
//    [task resume];
//    return task;
////    [[SAFNetworking shareInstance]downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
////        if (progress) {
////            progress(downloadProgress);
////        }
////    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
////        //这里要返回一个NSURL，其实就是文件的位置路径
////        NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
////        //使用建议的路径
////        path = [path stringByAppendingPathComponent:response.suggestedFilename];
////        NSLog(@"%@",path);
////        return [NSURL fileURLWithPath:path];//转化为文件路径
////    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
////        if (success) {
////            //存储到本地
////            [SCache saveFilePath:urlStr addition:nil filePath:filePath.absoluteString];
////            success([[NSData alloc]initWithContentsOfURL:filePath]);
////        }
////    }];
////    if (failure) {
////        failure(task.response,error);
////    }
//}

//+ (NSURLSessionDownloadTask * )DOWNLOAD_SYNC:(NSString*)urlStr Parameter:(NSDictionary *)param addition:(NSString*)addition filetype:(NSString*)filetype success:(SActionBlock1)success failure: (failureBlock)failure progress: (SActionBlock1)progress{
//    //查找本地有没有
//    id path = [SCache getFilePath:urlStr addition:nil];
//    NSURL *pathURL = [NSURL fileURLWithPath:path?:@""];
//    if (path && pathURL) {
//        success(pathURL);
//        DLog(@"本地路径：%@，绝对路径：%@",path,[pathURL absoluteString]);
//        return nil;
//    }
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //创建信号量
//    DLog(@"开始下载url：%@",urlStr);
//    // 1、 设置请求
//    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//    // 2、初始化
////    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
////    AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//    // 3、开始下载
//    NSURLSessionDownloadTask * task = [[SAFNetworking shareManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        if (progress) {
//            progress(downloadProgress);
//        }
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        //使用建议的路径
//        NSString * path = [SCache filePath:response.suggestedFilename];
//        NSLog(@"%@",path);
//        return [NSURL fileURLWithPath:path];//转化为文件路径
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        //如果下载的是压缩包的话，可以在这里进行解压
//        DLog(@"----%@---%d---%@",error.domain,error.code,error);
//        //下载成功
//        if (error == nil) {
//            if (success) {
//                //存储到本地 实际上存储的是文件名
//                [SCache saveFilePath:urlStr addition:nil filePath:response.suggestedFilename];
//                DLog(@"下载成功并保存在本地url：%@,文件名:%@",urlStr,response.suggestedFilename);
//                success(filePath);
//            }
//        }else{//下载失败的时候，只列举判断了两种错误状态码
//            NSString * message = nil;
//            if (error.code == - 1005) {
//                message = @"网络异常";
//            }else if (error.code == -1001){
//                message = @"请求超时";
//            }else{
//                message = @"未知错误";
//            }
//            if(failure){
//                failure(response,error);
//            }
//        }
//        dispatch_semaphore_signal(semaphore);//不管请求状态是什么，都得发送信号，否则会一直卡着进程
//    }];
//    [task resume];
//    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);  //等待
//    return task;
//}
@end

//@implementation SCache
//+(NSString*)FMDBPath{
//    return NSTemporaryDirectory();
//}
//
////创建文件名
//+(NSString*)createFileName:(NSString*)type{
//    return [NSString stringWithFormat:@"%@__%@%@",[UsefulMethodOC getFileNameDate],[[NSUUID UUID]UUIDString],type?[NSString stringWithFormat:@".%@",type]:@""];
//}
////创建文件路径
//+(NSString*)createFilePath:(NSString*)type{
//    return [NSString stringWithFormat:@"%@%@",[SCache FMDBPath],[SCache createFileName:type]];
//}
//+(NSString*)filePath:(NSString*)fileName{
//    return (fileName && fileName.length>0)?[[SCache FMDBPath] stringByAppendingPathComponent:fileName]:nil;
//}
////获取数据库
//+(FMDatabase*)initFMDB{
//    //    1，拿到数据库文件的路径
//    NSString *path = [[SCache FMDBPath] stringByAppendingPathComponent:@"tmp.db"];
//    //    2，拿到数据库对象，打开数据库，如果这个数据库不存在，就会自动创建
//    FMDatabase *db = [FMDatabase databaseWithPath:path];
//    if ([db open]) {
//        #if DEBUG
//                [HudBar showMsg:@"数据库打开成功"];
//        #endif
//        return db;
//    }else{
//        #if DEBUG
//                [HudBar showMsg:@"数据库打开失败"];
//        #endif
//        return nil;
//    }
//}
////初始化数据库和表
//+(BOOL)initFMDBAndKeyValueTable{
//    if ([UserDefaults boolForKey:@"KeyValueTable"] ) {
//        return YES;
//    }
//    FMDatabase *db = [SCache initFMDB];
//    if (db) {
//        if ([db executeStatements:@"create table if not exists KeyValueTable (k varchar primary key not null,v varchar not null);"]) {
//            [db close];
//            return YES;
//        }
//        [db close];
//    }
//    return NO;
//}
////获取缓存表
//+(void)excuteCacheTable:(NSString*)sql success:(SActionBlock1)success failure:(SActionBlock1)failure{
//    FMDatabase *db = [SCache initFMDB];
//    if (db) {
//        if ([db executeStatements:@"create table if not exists KeyValueTable (k varchar primary key not null,v varchar not null);"]) {
//            #if DEBUG
//                        [HudBar showMsg:@"数据库打开成功,文件缓存表创建成功"];
//            #endif
//            FMResultSet *set = [db executeQuery:sql];
//            if (success) {
//                success(@[set?:[FMResultSet new],db]);
//            }
//            [db close];//关闭数据库
//        }else{
//            [db close];//关闭数据库
//            #if DEBUG
//                        [HudBar showMsg:@"数据库打开成功,文件缓存表创建失败"];
//            #endif
//            if (failure) {
//                failure(nil);
//            }
//        }
//    }else{
//        if (failure) {
//            failure(nil);
//        }
//    }
//}
//
///**
// *
// insert into KeyValueTable (k,v) values (1,2)
// update
//
// */
////执行查询SQL 有FMResultSet *类型的返回 记得要关闭
//+(void)excuteSelectSQL:(NSString*)sql success:(SActionBlock1)success failure:(SActionBlock1)failure{
//    FMDatabase *db = [SCache initFMDB];
//    if (db) {
//        FMResultSet *set = [db executeQuery:sql];
//        if (success) {
//            success(@[set?:[FMResultSet new],db]);
//        }
//        [db close];
//    }else{
//        DLog(@"---%@",[db lastErrorMessage]);
//        if (failure) {
//            failure(nil);
//        }
//    }
//}
//
////执行查询SQL 有FMResultSet *类型的返回 记得要关闭
//+(void)excuteUpdateSQL:(NSString*)sql success:(SActionBlock1)success failure:(SActionBlock1)failure{
//    FMDatabase *db = [SCache initFMDB];
//    if (db) {
//        if ([db executeUpdate:sql]) {
//            DLog(@"数据库操作成功");
//            success(db);
//            [db close];
//        }else{
//            [db close];
//            failure(@"数据库执行失败");
//        }
//    }else{
//        DLog(@"---%@",[db lastErrorMessage]);
//        if (failure) {
//            failure(@"数据库打开失败");
//        }
//    }
//}
//
//+(void)saveKey:(NSString*)key value:(NSString*)value success:(SActionBlock1)success failure:(SActionBlock1)failure{
//    [SCache excuteSelectSQL:[NSString stringWithFormat:@"SELECT COUNT(*) FROM KeyValueTable where k = '%@'",key] success:^(NSArray *res) {
//        FMResultSet *set = res[0];
//        FMDatabase *db = res[1];
//        NSString *sql = @"";
//        if([set next]){
//            int totalCount = [set intForColumnIndex:0];
//            if (totalCount>0) {
//                //有则更新
//                sql = [NSString stringWithFormat:@"update KeyValueTable set v = '%@' where k = '%@'",value,key];
//            }else{
//                //没有则插入
//                sql = [NSString stringWithFormat:@"insert into KeyValueTable (k,v) values('%@','%@')",key,value];
//            }
//        }else{
//            //没有则插入
//            sql = [NSString stringWithFormat:@"insert into KeyValueTable (k,v) values('%@','%@')",key,value];
//        }
//        if ([db executeUpdate:sql]) {
//            if (success) {
//                success(nil);
//            }
//        }
//    } failure:failure];
//}
//+(NSString*)getKey:(NSString*)key addition:(id)addition{
//    return [NSString stringWithFormat:@"%@%@",addition?addition:@"",key];
//}
//+(NSString*)searchKey:(NSString*)key{
//    FMDatabase *db = [SCache initFMDB];
//    NSString *sql = [NSString stringWithFormat:@"SELECT v FROM KeyValueTable where k = '%@'",key];
//    if (db) {
//        FMResultSet *set = [db executeQuery:sql];
//        NSString *str;
//        if ([set next]) {
//            str = [set stringForColumn:@"v"];
//        }
//        [db close];
//        return str;
//    }else{
//        DLog(@"---%@",[db lastErrorMessage]);
//        return nil;
//    }
//}
//
////只有删除成功了才返回搜索到的值，否则即使搜索到了但没有删除成功也不返回值
//+(NSString*)searchKeyAndDelete:(NSString*)key{
//    FMDatabase *db = [SCache initFMDB];
//    NSString *sql = [NSString stringWithFormat:@"SELECT v FROM KeyValueTable where k = '%@'",key];
//    if (db) {
//        FMResultSet *set = [db executeQuery:sql];
//        NSString *str;
//        if ([set next]) {
//            str = [set stringForColumn:@"v"];
//        }
//        sql = [NSString stringWithFormat:@"delete from KeyValueTable where k=('%@')",key];
//        if ([db executeUpdate:sql]) {
//            [db close];
//            return str;
//        }else{
//            [db close];
//            return nil;
//        }
//    }else{
//        DLog(@"---%@",[db lastErrorMessage]);
//        return nil;
//    }
//}
////存储文件名
//+(NSString*)save:(NSString *)key addition:(id)addition data:(id)data type:(NSString*)type{
//    //生成key value 键值对 存起来,存文件名不存路径
//    NSString *fileDir = [SCache FMDBPath];//文件路径
//    NSString *fileName = [SCache createFileName:type];
//    NSString *filePath = [NSString stringWithFormat:@"%@%@",fileDir,fileName];
//    NSError *error = [[NSError alloc]init];
//    if ([data isKindOfClass:[NSData class]]&&[data writeToFile:filePath atomically:YES]) {
//        //存储键值对
//        [SCache saveKey:[SCache getKey:key addition:addition] value:fileName success:nil failure:nil];
//#if DEBUG
//        [HudBar showMsg:@"文件存储成功"];
//#endif
//        return filePath;
//    }else if ([data isKindOfClass:[NSURL class]] && [[NSFileManager defaultManager] moveItemAtURL:data toURL:[NSURL fileURLWithPath:filePath] error:&error]){
//        //存储键值对
//        [SCache saveKey:[SCache getKey:key addition:addition] value:fileName success:nil failure:nil];
//#if DEBUG
//        [HudBar showMsg:@"文件存储成功"];
//#endif
//        return filePath;
//    }else if ([data isKindOfClass:[NSString class]]) {
//        //如果在目录下就直接存储键值对，如果不在就重命名
//        if ([data hasPrefix:fileDir] && [data length]>fileDir.length) {
//            fileName = [data substringFromIndex:fileDir.length];
//            filePath = [NSString stringWithFormat:@"%@%@",fileDir,fileName];
//            //存储键值对
//            [SCache saveKey:[SCache getKey:key addition:addition] value:fileName success:nil failure:nil];
//        }else if ([[NSFileManager defaultManager] moveItemAtPath:data toPath:filePath error:&error]){
//            //存储键值对
//            [SCache saveKey:[SCache getKey:key addition:addition] value:fileName success:nil failure:nil];
//#if DEBUG
//            [HudBar showMsg:@"文件存储成功"];
//#endif
//        }else{
//#if DEBUG
//            DLog(@"%@",error);
//            [HudBar showMsg:@"文件存储失败"];
//#endif
//            return nil;
//        }
//        return filePath;
//    }else{
//        #if DEBUG
//        DLog(@"%@",error);
//                [HudBar showMsg:@"文件存储失败"];
//        #endif
//        return nil;
//    }
//}
////保存文件路径
//+(void)saveFilePath:(NSString*)key addition:(id)addition filePath:(NSString*)filePath{
//    //存储键值对
//    [SCache saveKey:[SCache getKey:key addition:addition] value:filePath success:nil failure:nil];
//}
//
////获取文件路径
//+(NSString*)getFilePath:(NSString *)key addition:(id)addition{
//    NSString *filePath = [SCache filePath:[SCache searchKey:[SCache getKey:key addition:addition]]];
//    return (filePath && [[NSFileManager defaultManager] fileExistsAtPath:filePath])?filePath:nil;
//}
////获取数据
//+(NSData*)getData:(NSString *)key addition:(id)addition{
//    NSString *filePath = [SCache filePath:[SCache searchKey:[SCache getKey:key addition:addition]]];
//    if (filePath && [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//        return [[NSData alloc]initWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
//    }
//    return nil;
//}
////删除键值对和文件，只有在键值对删除的情况下才删文件，防止键值对没删，文件被删除了
//+(BOOL)deleteFile:(NSString *)key addition:(id)addition{
//    //获取键值对
//    NSString *filePath = [SCache filePath:[SCache searchKeyAndDelete:[SCache getKey:key addition:addition]]];
//    if (filePath && filePath.length > 0) {
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        if ([fileManager removeItemAtURL:[NSURL fileURLWithPath:filePath] error:nil]) {
//            #if DEBUG
//                    [HudBar showMsg:@"文件删除成功"];
//            #endif
//            return YES;
//        }else{
//            #if DEBUG
//                    [HudBar showMsg:@"文件删除失败"];
//            #endif
//            return NO;
//        }
//    }
//    return NO;
//}
//+(BOOL)clearAll{
//    [UserDefaults setBool:NO forKey:@"KeyValueTable"];
//    FMDatabase *db = [SCache initFMDB];
//    NSString *sql = @"drop table KeyValueTable";
//    if (db) {
//        if ([db executeUpdate:sql]) {
//            [db close];
//            return YES;
//        }else{
//            [db close];
//        }
//    }else{
//        DLog(@"---%@",[db lastErrorMessage]);
//    }
//    return NO;
//}
//@end
